using System;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using Microsoft.Win32;

using ADODB;
using MSDASC;

using FreeFlow.Administration;

namespace FreeFlow.Administration.WinFormsControls
{
	/// <summary>
	/// Form used to login to a database.
	/// </summary>
	public class LoginForm : System.Windows.Forms.Form
	{
    private System.Windows.Forms.Button buildButton;
    private System.Windows.Forms.TextBox connStringTextBox;
    private System.Windows.Forms.Button okButton;
    private System.Windows.Forms.Button cancelButton;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;
    private System.Windows.Forms.CheckBox rememberCheckBox;
    private System.Windows.Forms.TabPage odbcTabPage;
    private System.Windows.Forms.TabPage connectionStringTabPage;
    private System.Windows.Forms.Panel panel1;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.Label label3;
    private System.Windows.Forms.TextBox userTextBox;
    private System.Windows.Forms.TextBox passwordTextBox;
    private System.Windows.Forms.ComboBox datasourceCombo;

    private const string freeflowRegistryKey = @"Software\FreeFlow";
    private const string eworkRegistryKey = @"Software\Metastorm\e-work\Utilities\Database";
    private const string connectionStringRegName = "ConnectionString";
    private const string rememberConnectionStringRegName = "RememberConnectionString";
    private const string userNameRegName = "UserName";
    private System.Windows.Forms.TabControl tabControl;
    private const string datasourceRegName = "DataSource";
    /// <summary>
    /// Initializes a new instance of the <see cref="LoginForm"/> class.
    /// </summary>
		public LoginForm()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			RegistryKey key = Registry.CurrentUser.OpenSubKey(freeflowRegistryKey);
      if (key != null)
      {
        if (key.GetValue(connectionStringRegName) != null)
          connStringTextBox.Text = key.GetValue(connectionStringRegName).ToString();
        if (key.GetValue(rememberConnectionStringRegName) != null)
          rememberCheckBox.Checked = Convert.ToBoolean(key.GetValue(rememberConnectionStringRegName));
      }

      Hashtable datasources = DSN.DSNs;
      foreach (DictionaryEntry item in datasources)
      {
        datasourceCombo.Items.Add(item.Key);
      }

      key = Registry.CurrentUser.OpenSubKey(eworkRegistryKey);
      if (key != null)
      {
        if (key.GetValue(userNameRegName) != null)
          userTextBox.Text = key.GetValue(userNameRegName).ToString();
        if (key.GetValue(datasourceRegName) != null)
          datasourceCombo.SelectedItem = key.GetValue(datasourceRegName).ToString();
      }

      Application.Idle += new EventHandler(Application_Idle);
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
      Application.Idle -= new EventHandler(Application_Idle);
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
      System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LoginForm));
      this.connStringTextBox = new System.Windows.Forms.TextBox();
      this.buildButton = new System.Windows.Forms.Button();
      this.okButton = new System.Windows.Forms.Button();
      this.cancelButton = new System.Windows.Forms.Button();
      this.rememberCheckBox = new System.Windows.Forms.CheckBox();
      this.tabControl = new System.Windows.Forms.TabControl();
      this.odbcTabPage = new System.Windows.Forms.TabPage();
      this.datasourceCombo = new System.Windows.Forms.ComboBox();
      this.passwordTextBox = new System.Windows.Forms.TextBox();
      this.userTextBox = new System.Windows.Forms.TextBox();
      this.label3 = new System.Windows.Forms.Label();
      this.label2 = new System.Windows.Forms.Label();
      this.label1 = new System.Windows.Forms.Label();
      this.connectionStringTabPage = new System.Windows.Forms.TabPage();
      this.panel1 = new System.Windows.Forms.Panel();
      this.tabControl.SuspendLayout();
      this.odbcTabPage.SuspendLayout();
      this.connectionStringTabPage.SuspendLayout();
      this.panel1.SuspendLayout();
      this.SuspendLayout();
      // 
      // connStringTextBox
      // 
      this.connStringTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                  | System.Windows.Forms.AnchorStyles.Right)));
      this.connStringTextBox.Location = new System.Drawing.Point(8, 8);
      this.connStringTextBox.Name = "connStringTextBox";
      this.connStringTextBox.Size = new System.Drawing.Size(474, 20);
      this.connStringTextBox.TabIndex = 1;
      // 
      // buildButton
      // 
      this.buildButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
      this.buildButton.FlatStyle = System.Windows.Forms.FlatStyle.System;
      this.buildButton.Location = new System.Drawing.Point(416, 32);
      this.buildButton.Name = "buildButton";
      this.buildButton.Size = new System.Drawing.Size(67, 23);
      this.buildButton.TabIndex = 2;
      this.buildButton.Text = "Build...";
      this.buildButton.Click += new System.EventHandler(this.buildButton_Click);
      // 
      // okButton
      // 
      this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
      this.okButton.FlatStyle = System.Windows.Forms.FlatStyle.System;
      this.okButton.Location = new System.Drawing.Point(336, 8);
      this.okButton.Name = "okButton";
      this.okButton.Size = new System.Drawing.Size(75, 23);
      this.okButton.TabIndex = 3;
      this.okButton.Text = "OK";
      this.okButton.Click += new System.EventHandler(this.okButton_Click);
      // 
      // cancelButton
      // 
      this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
      this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
      this.cancelButton.FlatStyle = System.Windows.Forms.FlatStyle.System;
      this.cancelButton.Location = new System.Drawing.Point(416, 8);
      this.cancelButton.Name = "cancelButton";
      this.cancelButton.Size = new System.Drawing.Size(75, 23);
      this.cancelButton.TabIndex = 4;
      this.cancelButton.Text = "Cancel";
      // 
      // rememberCheckBox
      // 
      this.rememberCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System;
      this.rememberCheckBox.Location = new System.Drawing.Point(8, 32);
      this.rememberCheckBox.Name = "rememberCheckBox";
      this.rememberCheckBox.Size = new System.Drawing.Size(392, 24);
      this.rememberCheckBox.TabIndex = 6;
      this.rememberCheckBox.Text = "Remember the connection string - This will be stored in plain text in the registr" +
          "y";
      // 
      // tabControl
      // 
      this.tabControl.Controls.Add(this.odbcTabPage);
      this.tabControl.Controls.Add(this.connectionStringTabPage);
      this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill;
      this.tabControl.Location = new System.Drawing.Point(0, 0);
      this.tabControl.Name = "tabControl";
      this.tabControl.SelectedIndex = 0;
      this.tabControl.Size = new System.Drawing.Size(498, 110);
      this.tabControl.TabIndex = 7;
      // 
      // odbcTabPage
      // 
      this.odbcTabPage.Controls.Add(this.datasourceCombo);
      this.odbcTabPage.Controls.Add(this.passwordTextBox);
      this.odbcTabPage.Controls.Add(this.userTextBox);
      this.odbcTabPage.Controls.Add(this.label3);
      this.odbcTabPage.Controls.Add(this.label2);
      this.odbcTabPage.Controls.Add(this.label1);
      this.odbcTabPage.Location = new System.Drawing.Point(4, 22);
      this.odbcTabPage.Name = "odbcTabPage";
      this.odbcTabPage.Size = new System.Drawing.Size(490, 84);
      this.odbcTabPage.TabIndex = 0;
      this.odbcTabPage.Text = "ODBC";
      // 
      // datasourceCombo
      // 
      this.datasourceCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
      this.datasourceCombo.Location = new System.Drawing.Point(168, 56);
      this.datasourceCombo.Name = "datasourceCombo";
      this.datasourceCombo.Size = new System.Drawing.Size(216, 21);
      this.datasourceCombo.Sorted = true;
      this.datasourceCombo.TabIndex = 5;
      // 
      // passwordTextBox
      // 
      this.passwordTextBox.Location = new System.Drawing.Point(168, 32);
      this.passwordTextBox.Name = "passwordTextBox";
      this.passwordTextBox.PasswordChar = '*';
      this.passwordTextBox.Size = new System.Drawing.Size(216, 20);
      this.passwordTextBox.TabIndex = 4;
      // 
      // userTextBox
      // 
      this.userTextBox.Location = new System.Drawing.Point(168, 8);
      this.userTextBox.Name = "userTextBox";
      this.userTextBox.Size = new System.Drawing.Size(216, 20);
      this.userTextBox.TabIndex = 3;
      // 
      // label3
      // 
      this.label3.Location = new System.Drawing.Point(88, 56);
      this.label3.Name = "label3";
      this.label3.Size = new System.Drawing.Size(72, 16);
      this.label3.TabIndex = 2;
      this.label3.Text = "Datasource:";
      // 
      // label2
      // 
      this.label2.Location = new System.Drawing.Point(88, 32);
      this.label2.Name = "label2";
      this.label2.Size = new System.Drawing.Size(64, 16);
      this.label2.TabIndex = 1;
      this.label2.Text = "Password:";
      // 
      // label1
      // 
      this.label1.Location = new System.Drawing.Point(88, 8);
      this.label1.Name = "label1";
      this.label1.Size = new System.Drawing.Size(64, 16);
      this.label1.TabIndex = 0;
      this.label1.Text = "User name:";
      // 
      // connectionStringTabPage
      // 
      this.connectionStringTabPage.Controls.Add(this.connStringTextBox);
      this.connectionStringTabPage.Controls.Add(this.buildButton);
      this.connectionStringTabPage.Controls.Add(this.rememberCheckBox);
      this.connectionStringTabPage.Location = new System.Drawing.Point(4, 22);
      this.connectionStringTabPage.Name = "connectionStringTabPage";
      this.connectionStringTabPage.Size = new System.Drawing.Size(490, 84);
      this.connectionStringTabPage.TabIndex = 1;
      this.connectionStringTabPage.Text = "Connection string";
      // 
      // panel1
      // 
      this.panel1.Controls.Add(this.cancelButton);
      this.panel1.Controls.Add(this.okButton);
      this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom;
      this.panel1.Location = new System.Drawing.Point(0, 110);
      this.panel1.Name = "panel1";
      this.panel1.Size = new System.Drawing.Size(498, 40);
      this.panel1.TabIndex = 8;
      // 
      // LoginForm
      // 
      this.AcceptButton = this.okButton;
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(498, 150);
      this.Controls.Add(this.tabControl);
      this.Controls.Add(this.panel1);
      this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
      this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
      this.MaximizeBox = false;
      this.MinimizeBox = false;
      this.Name = "LoginForm";
      this.ShowInTaskbar = false;
      this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
      this.Text = "Login";
      this.tabControl.ResumeLayout(false);
      this.odbcTabPage.ResumeLayout(false);
      this.odbcTabPage.PerformLayout();
      this.connectionStringTabPage.ResumeLayout(false);
      this.connectionStringTabPage.PerformLayout();
      this.panel1.ResumeLayout(false);
      this.ResumeLayout(false);

    }
		#endregion

    private void buildButton_Click(object sender, System.EventArgs e)
    {
      string connString = ConnectionStringBuilder.GetConnectionString();
      if (connString != null)
        connStringTextBox.Text = connString;
    }

    private void okButton_Click(object sender, System.EventArgs e)
    {
      if (server != null)
      {
        // try to connect
        try
        {
          if (IsOdbc)
            server.Connect(UserName, Password, Datasource);
          else
            server.Connect(ConnectionString);
        }
        catch(Exception ex)
        {
          DialogResult = DialogResult.None;
          MessageBox.Show("Unable to login - " + ex.Message);
          return;
        }
      }

      RegistryKey key = Registry.CurrentUser.CreateSubKey(freeflowRegistryKey);
      if (rememberCheckBox.Checked)
        key.SetValue(connectionStringRegName, connStringTextBox.Text);
      else
        key.SetValue(connectionStringRegName, string.Empty);
      key.SetValue(rememberConnectionStringRegName, rememberCheckBox.Checked);

      // save e-work settings
      key = Registry.CurrentUser.CreateSubKey(eworkRegistryKey);
      key.SetValue(userNameRegName, userTextBox.Text);
      key.SetValue(datasourceRegName, datasourceCombo.SelectedItem);

      DialogResult = DialogResult.OK;
      Close();
    }

    /// <summary>
    /// Gets the database connection string.
    /// </summary>
    /// <value>The database connection string.</value>
    public string ConnectionString
    {
      get
      {
        return connStringTextBox.Text;
      }
    }

    private bool IsOdbc
    {
      get
      {
        return tabControl.SelectedTab == odbcTabPage;
      }
    }

    private string UserName
    {
      get
      {
        return userTextBox.Text;
      }
    }

    private string Password
    {
      get
      {
        return passwordTextBox.Text;
      }
    }

    private string Datasource
    {
      get
      {
        return datasourceCombo.SelectedItem.ToString();
      }
    }

    private Server server;
    /// <summary>
    /// Gets or sets the server that this form will attempt to connect to.
    /// </summary>
    /// <value>The server.</value>
    public Server Server
    {
      get
      {
        return server;
      }
      set
      {
        server = value;
      }
    }

    private void Application_Idle(object sender, EventArgs e)
    {
      if (IsOdbc)
        okButton.Enabled = datasourceCombo.SelectedItem != null;
    }

    /// <summary>
    /// Shows the login dialog.
    /// </summary>
    /// <param name="server">The server that the form will attempt to connect to.</param>
    public static DialogResult ShowLoginDialog(Server server)
    {
      using (LoginForm loginForm = new LoginForm())
      {
        loginForm.Server = server;
        return loginForm.ShowDialog();
      }
    }
  }
}
